# -*- coding: utf-8 -*-
# @Time    : 2024/05/09 14:57
# @Author  : Mr.su
# @FileName: alexanderwang.py
# @FileDesc: 
from CollectSpiders.settings import LOG_FILE_PATH
from CollectSpiders.toots.methods import make_md5
from CollectSpiders.toots.connects import RedisClient
import scrapy, json, datetime, urllib.parse, logging, re


# noinspection PyAbstractClass,PyMethodMayBeStatic
class CrawlSpider(scrapy.Spider):
    name, domain = 'alexanderwang', 'www.alexanderwang.cn'
    redisClient = RedisClient()
    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36',
    }
    custom_settings = {
        'CONCURRENT_REQUESTS': 2,
        'LOG_FILE': LOG_FILE_PATH, 'LOG_LEVEL': 'WARNING'
    }

    def __init__(self, data=None, *args, **kwargs):
        """
        传入自定义参数
        :param data: 数据列表
        :param args:
        :param kwargs:
        """
        super(CrawlSpider, self).__init__(*args, **kwargs)
        self.data = json.loads(urllib.parse.unquote(data)) if data else {
            "pid": "2000", "status": 1, "wait_time": 3600, "brand": "alexanderwang",
            "childs": {
                "2001": {
                    "sid": "2001", "label": "女装", "upload": 1, "status": 1, "webtype": "taobao",
                    "url": "https://www.alexanderwang.com/hk-zh/women-newarrivals"
                }
            }
        }
        self.column = list(self.data['childs'].values())[0]

    def start_requests(self):
        if self.column['status'] == 1:
            new_url = 'https://www.alexanderwang.cn/cn-zh/search?cgid={}&start={}&format=json'
            yield scrapy.Request(
                new_url.format(self.column['url'].split('/')[-1], 0 * 12), headers=self.headers, callback=self.process_lis,
                meta={'new_url': new_url, 'pg': 0}
            )

    def process_lis(self, response):
        js = json.loads(response.text)
        has_more = True
        for data in js['search']['grid']['products']:
            result = self.redisClient.conn.sadd('products', make_md5(data['masterProductAbsoluteUrl']))
            if not result:
                has_more = False
                break
            img_lis = [i['fallbackUrl'].split('?')[0] for i in data['productView']['hi-res']]
            product = {
                '_id': make_md5(img_lis[0]),
                'pid': self.data['pid'],
                'sid': self.column['sid'],
                'status': '0',  # 0:未下载  1:已下载  6:下载失败
                'webtype': self.column['webtype'],
                'url': data['masterProductAbsoluteUrl'],
                'time': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                'brand': self.data['brand'],
                'image': img_lis,
                'domain': self.domain,
                'label': self.column['label'],
                'upload': self.column['upload'],
                'name': data['productName']
            }
            logging.warning('<{}>: 数据id: {}'.format(self.domain, product['_id']))
            yield product
        count = js['search']['grid']['settings']['productCount']
        pg_count = count // 12 - 1 if count % 12 == 0 else count // 12
        pg = response.meta['pg']
        if has_more and pg < pg_count:
            pg += 1
            new_url = response.meta['new_url']
            yield scrapy.Request(
                new_url.format(self.column['url'].split('/')[-1], pg * 12), headers=self.headers, callback=self.process_lis,
                meta={'new_url': new_url, 'pg': pg}
            )
